<template>
  <div class="blog-category-container" v-loading="isLoading">
    <RightList :list="list" @select="handleSelect" title="文章分类" class="rightList" />
  </div>
</template>

<script setup lang="ts">
import RightList from './RightList.vue'
import { getBlogCategories } from '@/api/blog'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { blogCategoriesItemType } from '@/types/blog'
const data = ref<blogCategoriesItemType[]>([] as blogCategoriesItemType[])
const $emit = defineEmits(['select'])
// 获取分类数据
const isLoading = ref(false)
onMounted(async () => {
  isLoading.value = true
  data.value = await getBlogCategories()
  isLoading.value = false
})

const router = useRouter()
const categoryId = computed(() => {
  return router.currentRoute.value.params.categoryId || -1
})
const limit = computed(() => {
  return router.currentRoute.value.query.limit || 10
})
const list = computed(() => {
  const totalArticleCount = data.value.reduce((a, b) => a + b.articleCount, 0)
  const result = [{ name: '全部', id: -1, articleCount: totalArticleCount }, ...data.value]

  const newresult = result.map((it) => ({
    ...it,
    isSelect: it.id == categoryId.value,
    aside: `${it.articleCount}篇`
  }))
  return newresult
})
function handleSelect(item: any) {
  $emit('select')
  const query = {
    page: 1,
    limit: limit.value
  }
  // 跳转到 当前的分类id  当前的页容量  newPage的页码
  if (item.id === -1) {
    router.push({
      name: 'Blog',
      query
    })
  } else {
    router.push({
      name: 'CategoryBlog',
      query,
      params: {
        categoryId: item.id
      }
    })
  }
}
</script>

<style scoped lang="scss">
.blog-category-container {
  min-width: 200px;
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  height: 100%;
  overflow-y: auto;
  background-color: #f6f6f6;
}
</style>
